package com.keyvez.simpledialer.android;

import android.app.ListActivity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.provider.Contacts.Phones;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;

public class Contacts extends ListActivity {
    private ContactsAdapter adapter;

    private static final int INITIAL_SIZE = 22;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        Eula.show(this);
        super.onCreate(savedInstanceState);
        String[] projection = new String[]{People._ID, People.TIMES_CONTACTED, People.DISPLAY_NAME, People.PRIMARY_PHONE_ID};
        String selection = People.PRIMARY_PHONE_ID + " IS NOT NULL";
        String[] selectionArguments = null;
        Cursor cursor = managedQuery(People.CONTENT_URI, projection, selection, selectionArguments, People.DISPLAY_NAME + " ASC");
        startManagingCursor(cursor);

        adapter = new ContactsAdapter(this, R.layout.contact, cursor);
        setListAdapter(adapter);
    }


    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        Intent intent = new Intent(Intent.ACTION_CALL);

        Cursor cursor = (Cursor) adapter.getItem(position);
        long phoneId = cursor.getLong(cursor.getColumnIndex(People.PRIMARY_PHONE_ID));
        intent.setData(ContentUris.withAppendedId(Phones.CONTENT_URI, phoneId));

		startActivity(intent);
    }

    private class ContactsAdapter extends CursorAdapter {
        private final LayoutInflater inflater;
        private Integer layout;

        public ContactsAdapter(Context context, Integer layout, Cursor cursor) {
            super(context, cursor, true);
            inflater = LayoutInflater.from(context);
            this.layout = layout;
    	}

        @Override
    	public void bindView(View view, Context context, Cursor cursor) {
    		TextView t = (TextView) view.findViewById(R.id.row);
            String name = cursor.getString(cursor.getColumnIndex(People.DISPLAY_NAME));
         	t.setText(name);
            // TODO: Make this factor more intelligent by using totalCallsMade
            int totalCallsMadeForPerson = cursor.getInt(cursor.getColumnIndex(People.TIMES_CONTACTED));
            t.setTextSize(totalCallsMadeForPerson+ INITIAL_SIZE);
    	}

    	@Override
    	public View newView(Context context, Cursor cursor, ViewGroup parent) {
            return inflater.inflate(layout, parent, false);
    	}
    }


    
}